package com.mengxuegu.blog.web.service;

import com.alibaba.fastjson.JSONObject;
import com.arronlong.httpclientutil.HttpClientUtil;
import com.arronlong.httpclientutil.common.HttpConfig;
import com.arronlong.httpclientutil.common.HttpHeader;
import com.arronlong.httpclientutil.exception.HttpProcessException;
import com.mengxuegu.blog.util.base.Result;
import com.mengxuegu.blog.util.enums.ResultEnum;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AuthService {

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    public Result refreshToken(String header,String refreshToken) throws HttpProcessException {
        ServiceInstance choose = loadBalancerClient.choose("auth-server");
        if(choose == null){
            return Result.error("未找到有效认证服务器");
        }
        String url = choose.getUri().toString() + "/auth/oauth/token";
        Map<String, Object> map=new HashMap<>();
        map.put("grant_type","refresh_token");
        map.put("refresh_token",refreshToken);

        Header[] build = HttpHeader.custom().contentType(HttpHeader.Headers.APP_FORM_URLENCODED)
                .authorization(header)
                .build();
        //请求配置
        HttpConfig httpconfig = HttpConfig.custom().headers(build).url(url).map(map);
        String token = HttpClientUtil.post(httpconfig);
        JSONObject jsonObject = JSONObject.parseObject(token);
        if(StringUtils.isNotEmpty(jsonObject.getString("error"))){
            return Result.build(ResultEnum.TOKEN_PAST);
        }
        return Result.ok(jsonObject);
    }
}
